package com.itluma.myshopping.dao.impl;

import com.itluma.myshopping.dao.ProductDAO;
import com.itluma.myshopping.entity.Product;
import com.itluma.myshopping.utils.JdbcUtils;
import com.itluma.myshopping.utils.StrUtils;
import lombok.SneakyThrows;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Ourshop6team
 * @author: 小陆
 * @create: 2021-03-15 21:07
 **/

public class ProductDAOImpl implements ProductDAO {

    private QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

    private Map<String, String> map = new HashMap<String, String>();

    {
        map.put("p_id", "pid");
        map.put("t_id", "tid");
        map.put("p_name", "pname");
        map.put("p_time", "ptime");
        map.put("p_image", "pimage");
        map.put("p_price", "pprice");
        map.put("p_state", "pstate");
        map.put("p_info", "pinfo");
    }

    @SneakyThrows
    public List<Product> showAll(Integer tid, Integer page, Integer pageSize) {
        String sql = "select * from product where t_id = ? limit ?,?";
        Object obj[];
        obj = new Object[]{tid, (page - 1) * pageSize, pageSize};
        List<Product> ProductList = queryRunner.query(sql, new BeanListHandler<Product>(Product.class, new BasicRowProcessor(new BeanProcessor(map))), obj);
        return ProductList;
    }

    @SneakyThrows
    @Override
    public Integer countByTid(Integer tid) {
        String sql = "select count(*) from product where t_id = ?";
        Long count = queryRunner.query(sql, new ScalarHandler<>(), tid);
        return count.intValue();
    }

    public static void main(String[] args) {
        ProductDAO productBeanDAO = new ProductDAOImpl();
//        List<Product> products = productBeanDAO.showAll(2, 1, 10);
//        System.out.println(products);

        Integer integer = productBeanDAO.countByTid(2);
        System.out.println(integer);
    }
}
